package com.likai.authority.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.likai.authority.pojo.User;
import com.likai.authority.service.IRoleService;
import com.likai.authority.service.IUserService;
import com.likai.authority.util.AnswerInfo;

/**
 * 登录Controller
 * @author likai
 * @since 2018-03-31
 */
@Controller
public class LoginController {
	
	@Autowired
	@Qualifier("userService")
	private IUserService userService ;
	
	@Autowired
	@Qualifier("roleService")
	private IRoleService roleService ;

	/**
	 * 页面跳转
	 * @return
	 */
	@RequestMapping(value="/loginJsp")
	public String loginJsp() {
		return "login" ;
	}
	
	/**
	 * 登录验证
	 * @param po 用户名、密码
	 * @param request
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ResponseEntity<AnswerInfo> login(
			User po,
			HttpServletRequest request
			) {
		AnswerInfo json = new AnswerInfo() ;
		User user = userService.login(po) ;
		if(user == null) {
			json.setData("用户名密码错误");
			json.setError("0");
		} else {
			//根据用户roleId查询角色信息
			String roleName = roleService.findByRoleId(user.getRoleid()).getRolename() ;
			user.setRolename(roleName);
			//讲用户信息存入Session
			request.getSession().setAttribute("user", user);
			json.setData("登录成功");
		}
		return new ResponseEntity<AnswerInfo>(json, HttpStatus.OK) ;
	}
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout(
			HttpServletRequest request
			) {
		request.getSession().invalidate();
		return "login" ;
	}
	
}
